# syntax=docker/dockerfile:1.4
# 第一阶段：构建应用
FROM node:22.17.0-alpine AS builder

# 设置工作目录
WORKDIR /app

# 安装pnpm（单独一层，便于缓存）
RUN npm install -g pnpm@latest

# 首先只复制package.json和pnpm-lock.yaml进行依赖安装
# 这样当源代码变更但依赖不变时，可以利用Docker缓存
COPY package.json pnpm-lock.yaml ./

# 安装依赖
RUN pnpm install --frozen-lockfile

# 复制源代码
COPY . .

# 构建应用
RUN pnpm run build:prod

# 第二阶段：运行应用
FROM node:22.17.0-alpine

# 安装运行时所需的基本工具
RUN apk add --no-cache bash curl tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    apk del tzdata

# 创建非root用户
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# 设置工作目录
WORKDIR /app

# 安装pnpm
RUN npm install -g pnpm@latest

# 从构建阶段复制编译后的代码和所有webpack复制的文件
COPY --from=builder /app/dist ./dist

# 复制启动脚本并设置权限
COPY docker-entrypoint.sh wait-for-it.sh ./
RUN chmod +x docker-entrypoint.sh wait-for-it.sh && \
    chown -R appuser:appgroup /app

# 创建日志和上传目录并设置权限
RUN mkdir -p /app/dist/logs /app/dist/uploads && \
    chown -R appuser:appgroup /app/dist/logs /app/dist/uploads && \
    chmod -R 755 /app/dist/logs /app/dist/uploads

# 切换到dist目录并安装生产环境依赖
WORKDIR /app/dist
RUN pnpm install --prod --frozen-lockfile
WORKDIR /app


# 切换到非root用户
USER appuser

# 暴露端口
EXPOSE 3000

# 健康检查 - 使用更轻量的方式
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD wget -q --spider http://127.0.0.1:3000/api/monitor/server || exit 1

# 设置入口点
ENTRYPOINT ["./docker-entrypoint.sh"] 